package com.iflytek.esb.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iflytek.esb.domain.Message;
import com.iflytek.esb.domain.PersistenceMessage;
import com.iflytek.esb.util.Consts;
import com.opensymphony.workflow.WorkflowException;

@Service
public class RequestServiceSoap implements RequestService {
	
	private static final Logger LOG = Logger.getLogger(RequestServiceSoap.class);
	private static final int SLEEP_TIME = 100;
	private static final int TIMEOUT = 120;
	
	@Autowired
	private QueueService queueService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private WorkflowService workflowService;

	public Result process(Message request, Message response) {
		
		//从请求路径中找到服务名
		String serviceName = request.getHeaders().get(Consts.HEADER_SERVICE_NAME);
		
		//试试看能不能找到对应的服务
		//TODO
		
		//找到服务定义，保存消息
		PersistenceMessage pm = messageService.createMessage(request.getHeaders(), request.getContent());
		LOG.debug("put message for service: " + serviceName);
		
		//在队列中创建任务
		Map<String, Object> q = new HashMap<String, Object>();
		q.put(Consts.MQ_KEY_MESSAGE, pm.getId());
		q.put(Consts.MQ_KEY_TRY, 1);
		q.put(Consts.MQ_KEY_TYPE, Consts.MQ_KEY_MESSAGE);
		queueService.inQueue(q, new Date(0));
		
		//剩下的事情就是等待
		boolean timeout = false;
		int count = 0;
		while (!timeout) {
			
			//查询返回值
			pm = messageService.getMessageById(pm.getId());
			if (pm.isResponsed()) {
				response.setContent(pm.getResponseContent());
				response.setHeaders(pm.getResponseHeaders());
				
				return Result.OK;
			}
			
			try {
				Thread.sleep(SLEEP_TIME);
			} catch (InterruptedException e) {
			}
			
			count ++;
			if (count > TIMEOUT * 1000 / SLEEP_TIME) {
				return Result.TIMEOUT;
			}
		}
		return Result.OK;
	}

}
